<template>
  <view>
    <customHeader v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></customHeader>
    <view class="invoiceImg" @click="downloadFile">
      <image src="https://100000043-1252208446.cos.ap-shanghai.myqcloud.com/maxmara-images/temp/inv.jpg" style="width:100%" mode="widthFix"></image>
    </view>
    <view class="btnBox">
      <view class="btn" @click="saveToEail">保存至邮箱</view>
      <view class="btn" @click="downLoadInvoice">下载发票</view>
    </view>
    <!-- 保存至邮箱 弹框 -->
    <view class="topBoxSmall" v-if="showDialog == 1">
      <view class="cont email">
        <view class="aos_mp aos_mp-close" @click="closeDialog"></view>
        <view class="box">
          <view class="sTitle">填写邮箱地址</view>
          <input type="text" :value="email" @input="bindEmail" class="inputText" />
          <view class="btn1" @click="submit">提交</view>
        </view>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>

<script>
import tip from '@/utils/tip';
import api from '@/api/api';
import customize from '@/utils/customize';
import Loading from '@/components/common/loading';
import customHeader from '@/components/common/custom';
import { SYSTEM_INFO, CUSTOMER_INFO, MERCHANT_INFO, USER_SPECICAL_INFO } from '@/utils/constant';
export default {
  components: {
    customHeader: customHeader
  },
  data() {
    return {
      isShowCustomNavBar: true,
      // 组件所需的参数
      navbarData: {
        showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
        title: '' //导航栏 中间的标题
      },
      orderId: '',
      taskSn: '',
      invoiceDetail: [],
      taskStatus: {
        0: '未提交',
        1: '提交失败',
        2: '提交成功',
        3: '处理中',
        4: '开票失败',
        5: '开票成功'
      },
      previousPages: '',
      showDialog: 0,
      email: '',
      nowPages:'',
    };
  },

  onLoad(option) {
    let that = this;
    that.orderId = option.orderNo;
    that.taskSn = option.tasksn;
    let pages = getCurrentPages();
    let prevpage = pages[pages.length - 2];
    var currPage = pages[pages.length - 1];
    this.nowPages = currPage.route;
    if (prevpage == undefined) {
      this.previousPages = '';
    } else {
      this.previousPages = prevpage.route ? prevpage.route : '';
    }
    that.getInvoiceDetial();
  },
   onShow(){
    getApp().cl_tracker.track('mini_program_view', {
          path:  this.nowPages,
          pageName: '下载发票',
        }) 
   },
  methods: {
		/**
		 * 展示弱提示
		 * @param {Object} msg 文案
		 */
		handleShowTextToast(msg){
			try{
				this.$refs.toastPopup.showToast(msg);
			}catch(e){}
		},
		/**
		 * 若提示按钮点击回调
		 * @param {Object} data.type 类型：confirm确定，cancel取消
		 * @param {Object} data.callBackData 呼气弹窗时传入的数据
		 */
		onToastPopupClick(data){},
    getInvoiceDetial: async function() {
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
      const invoiceList = await api.getInvoiceDetail(
        {
          method: 'POST',
          header: {
            jwt: customerInfo.jwt
          }
        },
        this.orderId,
        this.taskSn
      );
      if (invoiceList.code == 1000) {
        that.invoiceDetail = invoiceList.data;
        var s_createTime = that.invoiceDetail.createTime;
        that.invoiceDetail.createTime = s_createTime.substr(0, 10);
      } else {
        that.handleShowTextToast(invoiceList.msg);
      }
    },

    // 用浏览器查看发票pdf格式
    downloadFile() {
      tip.loading('预览中');
      wx.downloadFile({
        url: this.invoiceDetail.filePath,
        filePath: wx.env.USER_DATA_PATH + '/invoice.pdf', //自定义文件地址
        success(res) {
          var filePath = res.filePath;
          if (res.statusCode === 200) {
            var Path = res.tempFilePath;
            wx.openDocument({
              filePath: filePath,
              success: function(res) {}
            });
          }
        },
        complete(res) {
          tip.loaded();
        }
      });
    },

    // 保存至邮箱
    saveToEail() {
      let that = this;
      that.showDialog = 1;
    },
    closeDialog() {
      let that = this;
      that.email = '';
      that.showDialog = 0;
    },
    // 填写邮箱
    bindEmail(e) {
      let that = this;
      that.email = e.detail.value;
    },
    // 提交
    submit: async function() {
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
      if (that.email == '') {
        this.handleShowTextToast('邮箱不能为空');
        return;
      } else {
        const submitEmail = await api.invoiceSaveToEail(
          {
            method: 'POST',
            header: {
              jwt: customerInfo.jwt
            },
            query: {
              email: that.email,
              taskSn: that.taskSn
            }
          },
          this.orderId
        );
        if (submitEmail.code === 1000) {
          that.email = '';
          that.showDialog = 0;
          that.handleShowTextToast('提交成功');
        } else {
          that.email = '';
          that.showDialog = 0;
          that.handleShowTextToast(submitEmail.msg);
        }
      }
    },

    // 保存发票
    downLoadInvoice() {
      let that = this;
      tip.loading('下载中');
      wx.downloadFile({
        url: this.invoiceDetail.filePath,
        filePath: wx.env.USER_DATA_PATH + '/invoice.pdf', //自定义文件地址
        success(res) {
          if (res.statusCode === 200) {
            var Path = res.tempFilePath;
            var filePath = res.filePath;
            wx.saveFile({
              tempFilePath: filePath,
              success(res) {
                that.handleShowTextToast('下载成功');
              },
              fail(res) {
                that.handleShowTextToast('下载失败');
              }
            });
          }
        },
        complete(res) {
          tip.loaded();
        }
      });
    }
  }
};
</script>

<style>
.invoiceImg {
  margin: 70rpx 40rpx;
}
.btnBox {
  margin: 0 40rpx;
  display: flex;
  justify-content: space-between;
}
.btnBox .btn {
  width: 47%;
  border: 1px solid #000;
  color: #000;
  text-align: center;
  line-height: 80rpx;
  font-size: 28rpx;
}

/* 邮箱弹框 */
.topBoxSmall {
  background-color: rgba(0, 0, 0, 0.3);
  position: relative;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100vh;
  z-index: 999;
}
.topBoxSmall .cont {
  width: 80%;
  height: 400rpx;
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -200rpx 0 0 -40%;
  background-color: #fff;
}
.topBoxSmall .aos_mp-close {
  position: absolute;
  right: 5%;
  top: 30rpx;
  font-size: 28rpx;
}

.email {
  text-align: center;
  height: auto;
  font-size: 28rpx;
}
.email .box {
  padding: 60rpx 0;
  line-height: 60rpx;
}
.email .sTitle {
  color: #000;
}
.email .inputText {
  background-color: #f0f0f0;
  width: 80%;
  line-height: 66rpx;
  height: 66rpx;
  margin: 40rpx auto 60rpx;
}
.email .btn1 {
  border: 1px solid #000;
  background-color: #fff;
  width: 60%;
  margin: auto;
  color: #000;
}
</style>
